package com.xyhuo.leetcode.december;

/**
 * 在排序数组中查找元素的第一个和最后一个位置
 * https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
 *
 * @time 2023/12/13
 */
public class SearchRange {

//    public static void main(String[] args) {
//        SearchRange sr = new SearchRange();
//        int[] nums = {5, 7, 7, 8, 8, 10};
//        int[] num1 = {1, 1, 2};
//        sr.searchRange(num1, 1);
//    }

    public int[] searchRange(int[] nums, int target) {
        int len = nums.length, left = 0, right = len - 1;
        int[] ans = {-1, -1};
        while (left <= right) {
            int middle = (left + right) / 2;
            if (nums[middle] < target) {
                left = middle + 1;
            } else if (nums[middle] > target) {
                right = middle - 1;
            } else {
                int rightCount = 0;
                while (true) {
                    if (middle + rightCount + 1 >= len || nums[middle + rightCount + 1] != target) {
                        break;
                    }
                    rightCount++;
                }

                int leftCount = 0;
                while (true) {
                    if (middle - leftCount - 1 < 0 || nums[middle - leftCount - 1] != target) {
                        break;
                    }
                    leftCount++;
                }
                ans[0] = middle - leftCount;
                ans[1] = middle + rightCount;
                break;
            }
        }
        return ans;
    }

}
